import { ref, watch, computed } from "vue"
import { useRouter } from "vue-router"
import { TAG_NAME_KEYS } from "@/constant/index"
export function useTagsViews(){

    const router = useRouter()

    const tagsList =  ref([])
    // tagstitle
    const tagstitle = ref('')
    // 当前路由
    const currentRouter = computed(() => router.currentRoute.value)
    const setTabName = () => {
        const isSetTitle = currentRouter.value?.meta?.setTitle
        if(isSetTitle) {
            currentRouter.value.meta.title = sessionStorage.getItem(TAG_NAME_KEYS)
        }
        tagstitle.value = ''
    }
    const addTags = () => {
        const hasRouter = tagsList.value.filter(item => item.path === currentRouter.value.path)
        // 存在的情况
        if(hasRouter.length) { return  }
        // 更新标题
        setTabName()
        // 不存在
        tagsList.value.push(currentRouter.value)
    }
    addTags()
    // 路由跳转
    const toPage = (item) => {
        useSetTagsTitle(item.meta.title)
        router.push(item.path)
    }
    // 删除路由
    const delTagsViews = (item) => {
        const path = item.path
        const idx = tagsList.value.findIndex(r => r.path === path)
        // 删除的路由是否是当前路由
        const isActive = currentRouter.value.path === path
        // 删除路由
        tagsList.value.splice(idx, 1)
        //
        if(isActive) {
            const last = !tagsList.value.length ? { path: '/login' } : tagsList.value[0]
            toPage(last) 
        }
    }

    /**
     * 设置标签的标题
     */
    const useSetTagsTitle = (title) => {
        tagstitle.value = title
        sessionStorage.setItem(TAG_NAME_KEYS, title)
    }

    watch(() => router.currentRoute.value, () => {
        addTags()
    })

    return {
        tagsList,
        currentRouter,
        toPage,
        delTagsViews,
        useSetTagsTitle
    }


}